import React, { useState, useCallback, useEffect } from 'react';
import Cookies from 'js-cookie';

import styles from './cookie-duration.css';

export default function CookieDuration() {
  const [n, setn] = useState(0);

  const onSetCookie = useCallback(() => {
    const refreshToken = new Date().toString();
    Cookies.set('refreshTokenMock', refreshToken);
    console.log(new Date(), refreshToken);
    setn(n => n + 1);
  }, []);

  useEffect(() => {
    if (!n) return;
    const h = setInterval(() => {
      const refreshToken = Cookies.get('refreshTokenMock');
      console.log(new Date(), refreshToken);
    }, 10 * 60 * 1000);
    return () => {
      if (!n) return;
      clearInterval(h);
    };
  }, [n]);

  return (
    <div className={styles.normal}>
      <h1>Page cookie-duration</h1>
      <button onClick={onSetCookie}>set cookie</button>
    </div>
  );
}
